<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/12
 * Time: 10:47
 */

//------------------------
//考勤
//-------------------------

namespace app\attendance\controller;
use app\attendance\Base;
use com\gdl\kq\dataobject\platformsetting\platformsettingDTO;
use com\gdl\kq\interfaces\PlatformSettingServiceClient;
use com\gdl\newagk\dataobject\examination\FaceType;
use com\gdl\kq\dataobject\attendancegroup\AttendanceGroupDTO;
use com\gdl\kq\interfaces\AppAttendanceServiceClient;
use com\gdl\newagk\dataobject\examination\ExaminationRequestDTO;
use com\gdl\newagk\interfaces\ExaminationServiceClient;
use think\Config;
use think\Db;
use think\Exception;
use think\Loader;
date_default_timezone_set("PRC");
class AppAttendance extends Base
{
    //统计接口
	public function statisticsAppGet(){
		 $date = $this->request->param('date') ? str_replace('.','-',$this->request->param('date')) : date('Y-m',time());//日期 2018-07-16 如果为空则为今天
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : 0;
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';
		if(!$userId || $token==''){
			 $msg =  ['msg'=>'缺少参数','code'=>'500','data'=>[]];
            return json_encode($msg);
		}
        #验证
        if(!checkToken($token,$userId)){
            $msg['code'] = 501;
            $msg['msg'] ='用户登录失效，请重新登录'; return json_encode($msg);
        }
		try{
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
				$api = new AppAttendanceServiceClient(NULL);
				\ApiClient::build($api);
				$AttendanceGroupDTO = new AttendanceGroupDTO();
				$data = [
					'date'=>$date,
					'userId'=>$userId,
				];
				$AttendanceGroupDTO->data = $data;
				#调用接口
				$result = $api->statisticsAppGet($AttendanceGroupDTO);
				if($result->code){
					$msg =  ['msg'=>'获取成功','code'=>'200','data'=>json_decode($result->data[0][0])];
				} else {
					$msg =  ['msg'=>'获取失败','code'=>'400','data'=>[]];		
				}
        } catch (Exception $ex) {
           $msg =  ['msg'=>'异常','code'=>'500','data'=>[]];		
        }

        return json_encode($msg);
	}

	//获取日历状态值返回接口
    public function getCalendarStatusList(){
        $date = $this->request->param('date') ? str_replace('.','-',$this->request->param('date')) : date('Y-m',time());//日期 2018-07-16 如果为空则为今天
        $userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : 0;
        $token = $this->request->param('token') ? getStr($this->request->param('token')) : '';
        $type = $this->request->param('type') ? getStr($this->request->param('type')) : 1;//1安卓 2 ios
        if(!$userId || $token==''){
            $msg =  ['msg'=>'缺少参数','code'=>'500','data'=>[]];
            return json_encode($msg);
        }

        if(!checkToken($token,$userId)){
            $msg['code'] = 501;
            $msg['msg'] ='用户登录失效，请重新登录'; return json_encode($msg);
        }
        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
            $api = new AppAttendanceServiceClient(NULL);
            \ApiClient::build($api);
            $AttendanceGroupDTO = new AttendanceGroupDTO();
            $data = [
                'date'=>$date,
                'userId'=>$userId,
            ];
            $AttendanceGroupDTO->data = $data;

            #调用接口
            $result = $api->getCalendarStatusList($AttendanceGroupDTO);
            if($result->code){
                $row = [];
                $data = $result->data;
                if ($type==1){
                    $row = $data;
                }else{
                    foreach ($data as $key=>$value){
                        $row[$value['date']] = [
                          'status'  =>$value['status'],
                          'type'  =>$value['type'],
                        ];
                    }
                }
                $msg =  ['msg'=>'获取成功','code'=>'200','data'=>$row];
            } else {
                $msg =  ['msg'=>'获取失败','code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $msg =  ['msg'=>'异常','code'=>'500','data'=>[]];
        }

        return json_encode($msg);
    }

    /**
     * 获取人员每天的考勤组详细接口（包括选择日期是否为外勤）
     */
    public function sbqAppGetUserDaysAttendanceGroupInfo(){
        $msg =  ['msg'=>'获取成功','code'=>'200','data'=>[]];
        # 公共参数
        $token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

        #其他参数
        $platformId = $this->request->param('platformId') ? $this->request->param('platformId') : 0;//平台ID
        $date = $this->request->param('date') ? $this->request->param('date') : date('Y-m-d',time());//日期 2018-07-16 如果为空则为今天
        $userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : 0;
        $unitId = $this->request->param('unitId') ? getStr($this->request->param('unitId')) : 0;
        if (strpos($date,'.')){
            $date = str_replace('.','-',$date);
        }
        #验证
        if(!checkToken($token,$userId)){
            $msg['code'] = 501;
            $msg['msg'] ='用户登录失效，请重新登录'; return json_encode($msg);
        }
        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
            $api = new AppAttendanceServiceClient(NULL);
            $apiSetting = new PlatformSettingServiceClient(NULL);
            \ApiClient::build($api);
            \ApiClient::build($apiSetting);
            $platformsettingDTO = new platformsettingDTO();
            $AttendanceGroupDTO = new AttendanceGroupDTO();
            $data = [
                'platformId'=>$platformId,
                'date'=>$date,
                'userId'=>$userId,
                'unitId'=>$unitId,
            ];
            $AttendanceGroupDTO->data = $data;
            #调用接口
            $result = $api->sbqAppGetUserDaysAttendanceGroupInfo($AttendanceGroupDTO);

            $platformsettingDTO->key	= "faceType";
            $platformsettingDTO->platformId	= $platformId;
            $resultFaceType = $apiSetting->getPlatformSetting($platformsettingDTO);

            if($result->success==true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message;
                $msg['data'] = $result->data;
                $t = time();
                $startTime = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));//获取当天的0点时间戳
                $endTime = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));//获取当天的下午12点时间戳
                $date = strtotime($date);
                if ($date<$startTime){
                    $istoday = 2;
                }elseif ($date>$endTime){
                    $istoday = 3;
                }else{
                    $istoday = 1;
                }
                if(!empty($result->data)){
                    $Type = $resultFaceType->code?$resultFaceType->data[0]['value']:1;
                    $data = [
                      'time'=>$t,
                      'faceType'=>$Type,//1活体 2采集
                      'now'=>$istoday,//1 今天 2 过去 3未来
                      'data'=>json_decode($result->data[0]['data']),
                      'status'=>$result->data[0]['status']///status 1 有考勤记录 2今天休息  3暂无排班 4无需打卡 5无打卡记录
                    ];
                    $msg['data'] = $data;
                }
            }

        } catch (Exception $ex) {
            $msg['msg'] = $ex->getMessage();
        }

        return json_encode($msg);
    }

    //考勤打卡
    public function sbqAppDoSignIn(){
        $msg =  ['msg'=>'打卡成功','code'=>'200','data'=>[]];
        # 公共参数
        $token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

        #其他参数
        $platformId = $this->request->param('platformId') ? $this->request->param('platformId') : 0;//平台ID
        $time = $this->request->param('time') ? getStr($this->request->param('time')) : time();//打卡时间戳 不传默认当前时间
        //打卡地点 ['title'=>'重庆九龙坡智博中心','deviation'=>'500','Childcoordinate'=>['lng'=>'106.459223','lat'=>'29.509867']]
        $clockinCoordinate  = $this->request->param('coordinate') ? json_decode(htmlspecialchars_decode($this->request->param('coordinate')),true) :[];
        //打卡地点 ['title'=>'重庆九龙坡智博中心','deviation'=>'500','Childcoordinate'=>['lng'=>'106.459223','lat'=>'29.509867']]
        $coordinateSure  = $this->request->param('coordinateSure') ? json_decode(htmlspecialchars_decode($this->request->param('coordinateSure')),true) :[];
        //1打卡地点正常  2打卡地点异常
        $abnormalCoordinateIs = $this->request->param('abnormalCoordinateIs') ? getStr($this->request->param('abnormalCoordinateIs')) : 1;
        //人脸检测记录ID
        $vioLationId = $this->request->param('vioLationId') ? getStr($this->request->param('vioLationId')) : 0;
        //1人脸验证通过 2人脸验证未通过 3未验证
        $abnormalIdentityIs = $this->request->param('abnormalIdentityIs') ? getStr($this->request->param('abnormalIdentityIs')) : 0;
        //用户ID
        $memberId = $this->request->param('userId') ? getStr($this->request->param('userId')) : 0;
        //单位I
        $unitId = $this->request->param('unitId') ? getStr($this->request->param('unitId')) : 0;
        //备注文字
        $remark = $this->request->param('remark') ? getStr($this->request->param('remark')) : '';
        //打卡上传照片 ['http://ot7pftuwd.bkt.clouddn.com/jjtmbomo_4fdtlx7jyj6s5b5184868e44d.jpg','http://ot7pftuwd.bkt.clouddn.com/jjtmbomo_4fdtlx7jyj6s5b5184868e44d.jpg']
//        $photo = $this->request->param('photo') ? getStr($this->request->param('photo')) : [];
        $agId = $this->request->param('agId') ? getStr($this->request->param('agId')) : 0;
        $agName = $this->request->param('agName') ? getStr($this->request->param('agName')) : '';
        //1上班打卡 2下班打卡
        $clockinType = $this->request->param('clockinType') ? getStr($this->request->param('clockinType')) : 1;
        //1第一次打卡  2第二次打卡  3第三次打卡
        $clockinNum = $this->request->param('clockinNum') ? getStr($this->request->param('clockinNum')) : 1;
        //正常打卡时间点 ps:09:00:00
        $sureTime = $this->request->param('sureTime') ? getStr($this->request->param('sureTime')) : '';
        //1正常考勤 2外勤打卡
        $isGo = $this->request->param('isGo') ? getStr($this->request->param('isGo')) :1;
        //1不是休息日 2休息日
        $isRest = $this->request->param('isRest') ? getStr($this->request->param('isRest')) :1;

        #验证
        if(!checkToken($token,$memberId)){
            $msg['code'] = 501;
            $msg['msg'] ='用户登录失效，请重新登录'; return json_encode($msg);
        }
        if(!$sureTime || !$memberId|| !$agId){
            $msg['code'] = 400;
            $msg['msg'] ='参数错误'; return json_encode($msg);
        }

        $photo = [];
        $result = \Qiniu::instance()->upload(); //七牛上传
        if ($result){
            foreach ($result as $photoValues){
                $photo[] = Config::get('qiniu.QINIU_DOMAIN') . $photoValues['key'];
            }
        }

        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
            $api = new AppAttendanceServiceClient(NULL);
            \ApiClient::build($api);
            $AttendanceGroupDTO = new AttendanceGroupDTO();
            $data = [
                'time'=>$time,
                'clockinCoordinate'=>serialize($clockinCoordinate),
                'coordinateSure'=>serialize($coordinateSure),
                'isGo'=>$isGo,
                'clockinType'=>$clockinType,
                'clockinNum'=>$clockinNum,
                'sureTime'=>$sureTime,
                'isRest'=>$isRest,
                'abnormalCoordinateIs'=>$abnormalCoordinateIs,
                'vioLationId'=>$vioLationId,
                'abnormalIdentityIs'=>$abnormalIdentityIs,
                'memberId'=>$memberId,
                'unitId'=>$unitId,
                'platformId'=>$platformId,
                'agName'=>$agName,
                'agId'=>$agId,
                'photo'=>serialize($photo),
                'remark'=>$remark,
            ];

            $AttendanceGroupDTO->data = $data;
            #调用接口
            $result = $api->sbqAppDoSignIn($AttendanceGroupDTO);
            if($result->success==true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message;
                $msg['data'] = $result->data[0][0];
            }else{
                $msg['code'] = 400;
                $msg['msg'] = $result->message;
            }

        } catch (Exception $ex) {
            $msg['msg'] = $ex->getMessage();
        }

        return json_encode($msg);
    }

    //添加检测记录 人脸识别接口（需记录识别记录）
    public function sbqAppFaceRecognition(){
        $msg =  ['msg'=>'添加失败','code'=>'400','data'=>[]];
        # 公共参数
        $token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

        #其他参数
        $platformId = $this->request->param('platformId/d') ? $this->request->param('platformId/d') : 0;//平台ID
        $userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : 0;
        $unitId = $this->request->param('unitId') ? getStr($this->request->param('unitId')) : 0;
        $agId = $this->request->param('agId/d') ? $this->request->param('agId/d') : 0;
        $clockinNum = $this->request->param('clockinNum/d') ? $this->request->param('clockinNum/d') : 0;
        $clockinType = $this->request->param('clockinType/d') ? $this->request->param('clockinType/d') : 0;
        $agName = $this->request->param('agName') ? $this->request->param('agName') : '';

        $userName = $this->request->param('userName') ? $this->request->param('userName') : '';
        $truename = $this->request->param('truename') ? $this->request->param('truename') : '';
        $userIdcard = $this->request->param('userIdcard') ? $this->request->param('userIdcard') : '';
        //留底照片
        $photoCollect = $this->request->param('photo') ? $this->request->param('photo') : '';
        //留底照片状态 4: 未上传 1:未审核 2:未通过 3:已审核
        $photoStatus = $this->request->param('photoStatus') ? $this->request->param('photoStatus') : '';

        if(!$userId || !$platformId){
            $msg['msg']= "参数错误";
            return json_encode($msg);
        }
        #验证

        if(!checkToken($token,$userId)){
            $msg['code'] = 501;
            $msg['msg'] ='用户登录失效，请重新登录'; return json_encode($msg);
        }
        \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
        //获取用户的信息
        $AppAttendanceService = new AppAttendanceServiceClient(NULL);
        $ExaminationService = new ExaminationServiceClient(NULL);
        \ApiClient::build($AppAttendanceService);
        \ApiClient::build($ExaminationService);
        $AttendanceGroupDTO = new AttendanceGroupDTO();
        $ExaminationRequestDTO = new ExaminationRequestDTO();
        session_start();
        $faceSdk = strtolower('youtu');
        $faceType = 2;

        if(!$_FILES['file']['name']){//验证照片抓取失败
            $monitorInfo = [
                'memberId' => $userId,
                'agId' => $agId,
                'clockinNum' => $clockinNum,
                'clockinType' => $clockinType,
                'truename' => $truename,
                'userName' => $userName,
                'userIdcard' => $userIdcard,
                'currentImg' => "",
                'sourceImg' => $photoCollect, //留底照片
                'instructions' => "验证照片抓取失败！",
                'startTime' => date('Y-m-d H:i:s',time()),
            ];
            $monitorInfo['reason'] ="验证照片抓取失败！" ;
            $monitorInfo['verification'] = 0;
            $AttendanceGroupDTO->data = $monitorInfo;
            //$ExamsessionModel->modifyExamSession(['suspicion' => 2], session_id());
            $Id = $AppAttendanceService->addViolation($AttendanceGroupDTO);
            $Id = $Id->message;
            return json_encode(['code' => 200, 'massage' => "提交成功！",'data' =>['succ' => 0,'id' => $Id]]);

            // $data = ['msg'=>'检测照片没有上传，失败！','code'=>'400','data'=>[]];
            // return json_encode($data);
        }else{
//            $result = \Qiniu::instance()->upload(); //七牛上传
//            $address = $result[0]['key'];
//            $address = Config::get('qiniu.QINIU_DOMAIN') . $address;

            //修改 2018-08-06
            $faceImgA = base64_encode(file_get_contents($_FILES['file']['tmp_name'][0]));
            $faceImgB = base64_encode(file_get_contents($photoCollect));
            try {
                $ExaminationRequestDTO->name = $faceImgA;
                $ExaminationRequestDTO->field = $faceImgB;
                $ExaminationRequestDTO->type = $faceType;
                $faceMessage = Config::get('message.face');
                $similarity = 0;
                $judgeResult = -1;
                //比对的两张照片同时不为空，才可以调用比对接口
                //暂时传递URL图片
                //                if (!empty($faceImgA) && !empty($faceImgB)) {
					

                if ($photoStatus == 3) {
                    if (!empty($_FILES) && !empty($photoCollect)) {
                        $remark = '人脸有异常！';
                        $result = $ExaminationService->identify($ExaminationRequestDTO);

                        $similarity = $result->data[0]['similarity'];
                        $judgeResult = $faceSdk == 'facevisa' ? $result->data[0]['result'] : $result->data[0]['errorcode'];
                    } else {
                        $remark = '留底照片未上传/未通过.！';
                        $similarity = 0;
                    }
                }else{
                    $remark = '留底照片未上传/未通过！';
                    $similarity = 0;
                }

                $monitorInfo = [
                    'memberId' => $userId,
                    'truename' => $truename,
                    'userName' => $userName,
                    'agName' => $agName,
                    'agId' => $agId,
                    'clockinNum' => $clockinNum,
                    'clockinType' => $clockinType,
                    'currentImg' => "",//$address 后面慢慢上传
                    'sourceImg' => $photoCollect, //留底照片
                    'userIdcard' => $userIdcard,
                    'similarity' => $similarity,
                    'judgeResult' => $judgeResult,
                    'faceSdk' => $faceSdk,
                    'instructions' => $remark,
                    'startTime' => date('Y-m-d H:i:s',time()),
                ];
//                $souce_image = file_get_contents($_FILES['file']['tmp_name'][0]);
                if ($similarity >= FaceType::PASS) {
                    $monitorInfo['verification'] = 1;
                    $monitorInfo['reason'] = $faceMessage[FaceType::message1];
                    $monitorInfo['instructions'] = "----";
                    $AttendanceGroupDTO->data = $monitorInfo;
                    //$ExamsessionModel->modifyExamSession(['suspicion' => 1], session_id());
                    $Id = $AppAttendanceService->addViolation($AttendanceGroupDTO);
                    $Id = $Id->message;
                    $msg = [
                        'id' => $Id,
                        'image' => $faceImgA
                    ];
                    $host_config = Config::get('rabbitmq.config');
                    $upload = Config::get('rabbitmq.attendanceC');
                    $rabbitMq = new \RabbitMq($host_config, $upload['exchange_name'], $upload['queue_name'], $upload['routing_key']);
                    $rabbitMq->send($msg);
                    return json_encode(['code' => 200, 'massage' => $faceMessage[FaceType::message1],'data' =>['succ' => 1,'id' => $Id]]);
                } else {
                    $monitorInfo['reason'] = $faceMessage[FaceType::message2];
                    $monitorInfo['verification'] = 0;
                    $monitorInfo['instructions'] = $remark;
                    $AttendanceGroupDTO->data = $monitorInfo;
                    $Id = $AppAttendanceService->addViolation($AttendanceGroupDTO);
                    $Id = $Id->message;
                    $msg = [
                        'id' => $Id,
                        'image' => $faceImgA
                    ];
                    $host_config = Config::get('rabbitmq.config');
                    $upload = Config::get('rabbitmq.attendanceC');
                    $rabbitMq = new \RabbitMq($host_config, $upload['exchange_name'], $upload['queue_name'], $upload['routing_key']);
                    $rabbitMq->send($msg);
                    return json_encode(['code' => 200, 'massage' => $faceMessage[FaceType::message2],'data' =>['succ' => 0,'id' => $Id]]);
                }
            } catch (Exception $ex) {
                return json_encode(['msg' => '失败', 'code' => '400']);
            }
        }
    }


    //修改用户考勤记录的备注
    public function sbqAppEditUserRecordRemark(){
        $id = $this->request->param('id') ? getStr($this->request->param('id')) : 0;//记录Id
        $remark = $this->request->param('remark') ? getStr($this->request->param('remark')) : '';//描述
        $memberId = $this->request->param('userId') ? getStr($this->request->param('userId')) : 0;//用户Id
        $token = $this->request->param('token') ? getStr($this->request->param('token')) : '';
        if(!$memberId || $token==''){
            $msg =  ['msg'=>'缺少参数','code'=>'500','data'=>[]];
            return json_encode($msg);
        }

        if(!checkToken($token,$memberId)){
            $msg['code'] = 501;
            $msg['msg'] ='用户登录失效，请重新登录'; return json_encode($msg);
        }
        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
            $api = new AppAttendanceServiceClient(NULL);
            \ApiClient::build($api);
            $AttendanceGroupDTO = new AttendanceGroupDTO();
            $data = [
                'id'=>$id,
                'memberId'=>$memberId,
                'remark'=>$remark,
            ];
            $AttendanceGroupDTO->data = $data;
            #调用接口
            $result = $api->editAppUserRecordRemark($AttendanceGroupDTO);
            if($result->code){
                $msg =  ['msg'=>'修改成功','code'=>'200','data'=>[]];
            } else {
                $msg =  ['msg'=>'获取失败','code'=>'400','data'=>[]];
            }
        } catch (Exception $ex) {
            $msg =  ['msg'=>'异常','code'=>'500','data'=>[]];
        }

        return json_encode($msg);
    }
}